package com.tianyang.yukuaifuzs.common.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;

import com.gamerole.orcameralib.CameraActivity;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.tianyang.yukuaifuzs.R;
import com.tianyang.yukuaifuzs.business.login.bean.LoginOutput;
import com.tianyang.yukuaifuzs.business.main.adapter.ShareAdapter;
import com.tianyang.yukuaifuzs.common.cache.CacheManage;
import com.tianyang.yukuaifuzs.common.cache.CacheModel;
import com.tianyang.yukuaifuzs.common.interfaces.CommonConfig;
import com.tianyang.yukuaifuzs.jump.shareutil.ShareUtil;
import com.tianyang.yukuaifuzs.jump.shareutil.share.ShareListener;
import com.tianyang.yukuaifuzs.jump.shareutil.share.SharePlatform;
import com.tianyang.yukuaifuzs.module.dialog.RemindDialog;
import com.tianyang.yukuaifuzs.module.dialog.interfaces.TwoBtnClickListener;
import com.tianyang.yukuaifuzs.utils.AppContextUtil;
import com.tianyang.yukuaifuzs.utils.IntentTool;
import com.tianyang.yukuaifuzs.utils.ScreenUtil;
import com.tianyang.yukuaifuzs.utils.ToastUtil;

import java.io.IOException;
import java.io.InputStream;


/**
 * Description：视图工具类
 * Created by 薛勇军 on 2021/5/8
 */
public class CommonViewUtils {

    public static boolean isLogin() {
        LoginOutput loginOutput = CacheManage.getInstance().getCache(CacheModel.LOGIN_KEY);
        if (loginOutput != null) {
            return true;
        }
        return false;
    }
    public static String getAuthorization() {
        LoginOutput output = CacheManage.getInstance().getCache(CacheModel.LOGIN_KEY);
        if (output != null) {
            return output.getTokenHead() + output.getToken();
        }
        return "";
    }

    /**
     * 自适应控件宽度
     */
    private static int getWindowWidthFour(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int dec = ScreenUtil.dp2px(60);
        return (width - dec) / 4;
    }

    /**
     * 判断是否在线
     */
    public static boolean isLoginOnline(Context context) {
        LoginOutput loginOutput = CacheManage.getInstance().getCache(CacheModel.LOGIN_KEY);
        if (loginOutput == null || TextUtils.isEmpty(loginOutput.getToken())) {
            new RemindDialog(context).content("登录失效，请重新登录!")
                    .listener(new TwoBtnClickListener() {
                        @Override
                        public void onLeftClick() {

                        }

                        @Override
                        public void onRightClick() {
                            AppContextUtil.exit(context);
                        }
                    }).show();
            return false;
        }
        return true;
    }

    /**
     * 校验是否签约
     * @return
     */
    public static boolean isSignType(String signType) {
        if (!TextUtils.isEmpty(signType) && signType.startsWith("http")) {
            return false;
        }
        return true;
    }

    /**
     * 拍照
     */
    public static void onPhotographClick(Context mContext, String currentPhotoType, Uri imageUri, String cameraOcrPath) {
        if (TextUtils.equals(CommonConfig.TYPE_IDFROPIC, currentPhotoType)) {
            Intent intent = new Intent(mContext, CameraActivity.class);
            intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, cameraOcrPath);
            intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
            IntentTool.startActivityForResult(mContext, intent, CommonConfig.REQUESTCODE_CERTIFICATE_PICKER);
        } else if (TextUtils.equals(CommonConfig.TYPE_IDCONPIC, currentPhotoType)) {
            Intent intent = new Intent(mContext, CameraActivity.class);
            intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, cameraOcrPath);
            intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
            IntentTool.startActivityForResult(mContext, intent, CommonConfig.REQUESTCODE_CERTIFICATE_PICKER);
        } else if (TextUtils.equals(CommonConfig.TYPE_CRDFROPIC, currentPhotoType)) {
            Intent intent = new Intent(mContext, CameraActivity.class);
            intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, cameraOcrPath);
            intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_BANK_CARD);
            IntentTool.startActivityForResult(mContext, intent, CommonConfig.REQUESTCODE_CERTIFICATE_PICKER);
        } else {
            onTakePhotoClick(mContext, imageUri);
        }
    }

    /**
     * 拍照
     */
    public static void onTakePhotoClick(Context mContext, Uri imageUri) {
        PackageManager packageManager = mContext.getPackageManager();
        if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            //启动相机程序
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            //设定图片的输出地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            IntentTool.startActivityForResult(mContext, intent, CommonConfig.REQUESTCODE_CERTIFICATE_PICKER);
        } else {
            ToastUtil.show("当前设备不支持给此应用提供拍照功能，请检查系统权限");
        }
    }

    /**
     * 通过Uri和selection来获取真实的图片路径
     */
    public static String getImagePath(Context mContext, Uri uri, String selection) {
        String path = null;
        Cursor cursor = mContext.getContentResolver().query(uri, null, selection,null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    /**
     * 判断文件是否存在
     */
    public static boolean isFileExists(Context mContext, Uri uri) {
        if (uri == null) {
            return false;
        }
        try {
            InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
            if (inputStream != null) {
                inputStream.close();
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void shareToWeChat(Context context, String url) {
        shareToWeChat(context, url, null);
    }

    public static void shareToWeChat(Context context, Bitmap bitmap) {
        shareToWeChat(context, null, bitmap);
    }

    public static void shareToWeChat(Context context, String url, Bitmap bitmap) {
        if (!isWXAppInstalledAndSupported(context)) {
            ToastUtil.show("本机未安装微信，无法分享！");
            return;
        }
        final ShareAdapter mShareAdapter = new ShareAdapter(context);
        DialogPlus dialog = DialogPlus.newDialog(context)
                .setAdapter(mShareAdapter)
                .setHeader(R.layout.view_dialogplus_header)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                        if (position < 0) return;
                        prepareImage(context, mShareAdapter.getItem(position).getPlatform(), url, bitmap);
                    }
                })
                .setExpanded(false)
                .create();
        dialog.show();
    }

    /**
     * 分享图片bitmap
     */
    private static void prepareImage(Context context, @SharePlatform.Platform int module, String url, Bitmap bitmap) {
        ShareListener shareListener = new ShareListener() {
            @Override
            public void shareSuccess() {
                ToastUtil.show("分享成功");
            }

            @Override
            public void shareFailure(Exception e) {
                ToastUtil.show("分享失败");
            }

            @Override
            public void shareCancel() {
                ToastUtil.show("取消分享");
            }
        };
        if (bitmap != null) {
            ShareUtil.shareImage(context, module, bitmap, shareListener);
        } else {
            ShareUtil.shareImage(context, module, url, shareListener);
        }
    }

    /**
     * 本机是否支持微信分享
     */
    public static boolean isWXAppInstalledAndSupported(Context context) {
        boolean isWXAppInstalled = true;
        try {
            PackageManager manager = context.getPackageManager();
            manager.getPackageInfo("com.tencent.mm", PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            isWXAppInstalled = false;
        }
        return isWXAppInstalled;
    }
}
